package com.bharatonjava.swift.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.bharatonjava.swift.domain.Role;
import com.bharatonjava.swift.domain.User;
import com.bharatonjava.swift.service.UserService;

public class UserBean {

	private UserService userService;

	private User user;
	private String confirmPassword;

	private List<User> users;

	private List<Role> roles;
	private List<Role> selectedRoles;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<User> getUsers() {
		getAllUsers();
		return users;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public List<Role> getSelectedRoles() {
		return selectedRoles;
	}

	public void setSelectedRoles(List<Role> selectedRoles) {
		this.selectedRoles = selectedRoles;
	}

	@PostConstruct
	private void intializeBean() {
		user = new User();
		user.setRoles(new ArrayList<Role>());
		roles = userService.getAllRoles();
	}

	@PreDestroy
	private void destroyBean() {

	}

	public HttpSession getSession() {
		HttpSession session = null;
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		session = request.getSession();
		return session;
	}

	/**
	 * logout current user
	 */
	public void logout() {
		
		System.out.println("user Logged out.");
		getSession().invalidate();
	}

	/**
	 * Fetches a list of all users
	 */
	public void getAllUsers() {
		users = userService.getAllUsers();
	}

	/**
	 * Add new user
	 */
	public void addUser() {
		
		if(!userService.userExists(user))
		{
			
		user.setRoles(selectedRoles);
		userService.addUser(user);
		}
		else{
			System.out.println("user already exists: "+ user.getUserName());
		}
		
	}
}
